import {AfterViewInit, ChangeDetectorRef, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {PageEntity} from '../../../core/domain/page.entity';
import {StatusEnum} from '../../../core/enum/status.enum';
import {NzMessageService} from 'ng-zorro-antd';
import {PaginationUtils} from '../../../utils/paginationUtils';
import {StorageUtil} from '../../../utils/storage.util';
import {OtherUtil} from '../../../utils/other.util';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { StudentEvaluteService } from './student-evalute.service';
import {FilterEnum, FilterTypeEnum} from '../../../core/enum/filter.enum';
import { PostDown } from '../../../utils/postdown';

declare var $: any;

@Component({
  selector: 'app-student-evaluate',
  templateUrl: './student-evaluate.component.html',
  styleUrls: ['./student-evaluate.component.scss'],
  providers: [StudentEvaluteService,PostDown]
})
/**********学生评价统计*************/
export class StudentEvaluateComponent implements OnInit {
  formname = null;
  pageInfo: PageEntity = new PageEntity();
  pageInfoStu: PageEntity = new PageEntity();
  allList = [];
  evaluteList = [];
  detailList = [];
  displayList: Array<any> = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  isAllCheck = false;
  isIndeterminate = false;
  canDelete = false;
  nzWidthConfigs = [];
  yearListSearch = [];
  semestSearch = [];
  // 新增
  validateForm: FormGroup;
  searchObj: TopSearchObj = new TopSearchObj();
  searchStuObj:TopSearchStu = new TopSearchStu();
  semesterList = [];
  editState = '全部';
  mainStatus = 1; // 1.显示主页面，2.显示学生评价列表,3:显示详情页面
  tabs = ['全部', '已评价', '未评价'];
  studentScore = 0;
  // 发布评价
  checked = false;

  constructor(
    private service: StudentEvaluteService,
    private message: NzMessageService,
    private cd: ChangeDetectorRef,
    private ref: ElementRef,
    private httpclient: HttpClient,
    private fb: FormBuilder,
    private postDown: PostDown
  ) {
  }

  ngOnInit() {
    this.initForm();
    this.getYearSearch();
    this.page(this.pageInfo);
  }

  initForm() {
    this.validateForm = this.fb.group({
      value1: [null, [Validators.required]],
      value2: [null, [Validators.required]],
      value3: [null, [Validators.required]],
      value4: [null, [Validators.required]],
      value5: [null, [Validators.required]],
      value6: [null, [Validators.required]]
    });
  }

   /**
   * 查询学年学期列表
   */
    getYearSearch() {
      this.service.year().subscribe(res => {
        if (res.status === StatusEnum.SUCCESS) {
          this.yearListSearch = res.datas;
          this.semestSearch = [];
        }
      });
    }

    yearSearchChange(e) {
      this.searchObj.semesterId = null;
      this.yearListSearch.forEach(item => {
        if (e == item.schoolYear) {
          this.semestSearch = item.semester;
        }
      });
    }

  /*****分页查询*********/
  page(page: PageEntity): void {
    page.multiSortMeta = [
      {
        field: 'gmtCreate',
        order: -1
      }
    ];
    this.service.getPage(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.allList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
        // this.nzWidthConfigs = ['60px', '100px', '100px', '150px', '200px', '100px', '100px', '180px', '100px', '100px', '100px', '150px',
        // '120px', '120px', '180px', '150px', '120px'];
        this.nzWidthConfigs = ['60px', '100px', '100px', '150px', '200px', '100px', '100px', '180px', '100px', '100px', '100px', '180px', '150px', '120px'];
      }
    });
  }


  /*******第几页*******/
  searchPageIndex(event: any) {
    this.pageInfo.first = event;
    this.page(this.pageInfo);
  }

  /*******每页几条*****/
  searchPageSize(event: any) {
    this.pageInfo.rows = event;
    this.pageInfo.first = 1;
    this.page(this.pageInfo);
  }

  currentPageDataChange($event): void {
    this.displayList = $event;
    this.refreshStatus();
  }
  /*******第几页*******/
  searchPageIndexStu(event: any) {
    this.pageInfoStu.first = event;
    this.pageStu(this.pageInfoStu);
  }

  /*******每页几条*****/
  searchPageSizeStu(event: any) {
    this.pageInfoStu.rows = event;
    this.pageInfoStu.first = 1;
    this.pageStu(this.pageInfoStu);
  }

  currentPageDataChangeStu($event): void {
    this.displayList = $event;
    this.refreshStatus();
  }

  /*******状态改变******/
  refreshStatus(): void {
    this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.studentId]);
    this.isIndeterminate =
      this.displayList.some(item => this.mapOfCheckedId[item.studentId]) &&
      !this.isAllCheck;
    this.checkDelete();
  }

  /**
 * 全选
 * @param value： value
 */
  checkAll(value: boolean): void {
    this.displayList.forEach(item => (this.mapOfCheckedId[item.studentId] = value));
    this.refreshStatus();
  }

  /**
   * 主页根据id删除逻辑
   */
  delByIdsLogic() {
    const arr = [];
    for (const val in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[val]) {
        arr[arr.length] = val;
      }
    }
    return arr;
  }



  /********判断是否选择了数据需要删除**********/
  checkDelete(): void {
    this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
  }

  /*******点击查询*********/
  clickSearch() {
    this.pageInfo.first = 1;
    this.searchObj.semesterId ? this.pageInfo.filters['semesterId'.toString()] = {
      matchMode: FilterEnum.CONTAINS,
      value: this.searchObj.semesterId,
      whereType: FilterTypeEnum.AND
    } : delete this.pageInfo.filters['semesterId'.toString()];
    this.searchObj.schoolYear ? this.pageInfo.filters['schoolYear'.toString()] = {
      matchMode: FilterEnum.CONTAINS,
      value: this.searchObj.schoolYear,
      whereType: FilterTypeEnum.AND
    } : delete this.pageInfo.filters['schoolYear'.toString()];
    this.searchObj.number ? this.pageInfo.filters['number'.toString()] = {
      matchMode: FilterEnum.CONTAINS,
      value: this.searchObj.number,
      whereType: FilterTypeEnum.AND
    } : delete this.pageInfo.filters['number'.toString()];
    this.searchObj.name ? this.pageInfo.filters['name'.toString()] = {
      matchMode: FilterEnum.CONTAINS,
      value: this.searchObj.name,
      whereType: FilterTypeEnum.AND
    } : delete this.pageInfo.filters['name'.toString()];
    this.searchObj.teacherName ? this.pageInfo.filters['teacherName'.toString()] = {
      matchMode: FilterEnum.CONTAINS,
      value: this.searchObj.teacherName,
      whereType: FilterTypeEnum.AND
    } : delete this.pageInfo.filters['teacherName'.toString()];
    // this.searchObj.classesName ? this.pageInfo.filters['classesName'.toString()] = {
    //   matchMode: FilterEnum.CONTAINS,
    //   value: this.searchObj.classesName,
    //   whereType: FilterTypeEnum.AND
    // } : delete this.pageInfo.filters['classesName'.toString()];

    this.page(this.pageInfo);
  }

  /********点击重置**************/
  resetSearch() {
    this.pageInfo.first = 1;
    this.pageInfo = new PageEntity();
    this.searchObj = new TopSearchObj();
    this.semestSearch = [];
    this.page(this.pageInfo);
  }

  /*******点击查询*********/
  clickSearchStu() {
    this.pageInfoStu.first = 1;
    this.searchStuObj.studentNumber ? this.pageInfoStu.filters['studentNumber'.toString()] = {
      matchMode: FilterEnum.CONTAINS,
      value: this.searchStuObj.studentNumber,
      whereType: FilterTypeEnum.AND
    } : delete this.pageInfoStu.filters['studentNumber'.toString()];
    this.searchStuObj.studentName ? this.pageInfoStu.filters['studentName'.toString()] = {
      matchMode: FilterEnum.CONTAINS,
      value: this.searchStuObj.studentName,
      whereType: FilterTypeEnum.AND
    } : delete this.pageInfoStu.filters['studentName'.toString()];

    this.pageStu(this.pageInfoStu);
  }

  /********点击重置**************/
  resetSearchStu() {
    this.pageInfoStu.first = 1;
    delete this.pageInfoStu.filters['studentNumber'.toString()];
    delete this.pageInfoStu.filters['studentName'.toString()];
    this.searchStuObj = new TopSearchStu();
    this.pageStu(this.pageInfoStu);
  }


  /**
   * 点击编辑
   */
  edit(id: string) {
    this.mainStatus = 2
    this.pageInfoStu.first = 1;
    this.pageInfoStu.filters['examCourseId'.toString()] = {
      matchMode: FilterEnum.EQUALS,
      value: id,
      whereType: FilterTypeEnum.AND
    };
    this.pageInfoStu.filters['searchType'.toString()] = {
      matchMode: FilterEnum.EQUALS,
      value: '全部',
      whereType: FilterTypeEnum.AND
    };
    this.pageStu(this.pageInfoStu)
  }

  /*****学生评价分页查询*********/
  pageStu(page: PageEntity): void {
    this.service.getEvalute(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.evaluteList = res.datas.data;
        this.pageInfoStu.totalRecords = res.datas.totalRecords;
      }
    });
  }

  /**
 * 点击详情
 */
  detail(id: string) {
    this.mainStatus = 3
    this.pageDetail(id)
  }

   /*****学生评价详情查询*********/
  pageDetail(id: string): void {
    this.service.getDetail({id:id}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.studentScore = res.datas.score
        this.detailList = res.datas.detailList;
        console.log(this.detailList)
      }
    });
  }

  /**
   * 点击删除一个
   * @param ids： id
   */
   deleteOne(id: string) {
    this.service.delete({id:id}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.page(this.pageInfo);
      }
    });
  }

  changeTab(i:Number) {
    if ( i == 0 ) {
      this.editState = '全部'
    } else if ( i == 1 ) {
      this.editState = '已评价'
    } else {
      this.editState = '未评价'
    }
    this.pageInfoStu.first = 1
    this.pageInfoStu.filters['searchType'.toString()] = {
      matchMode: FilterEnum.EQUALS,
      value: this.editState,
      whereType: FilterTypeEnum.AND
    };
    this.pageStu(this.pageInfoStu)
  }

  /**
   * 1：导出选中；2：导出当前页；3：导出全部
   */
   exportShow(num: number): void {
    const obj = {
      mode: num,
      pager: {},
      sourceIds: []
    };
    if (num === 1) {
      const arr = this.delByIdsLogic();
      if (arr.length < 1) {
        this.message.warning('请勾选要导出的数据！');
        return;
      }
      obj.pager = this.pageInfoStu;
      obj.sourceIds = Object.keys(this.mapOfCheckedId).filter(k => this.mapOfCheckedId[k] === true);
    } else if (num === 3) {
      obj.pager = this.pageInfoStu;
      obj.sourceIds = [];
    }
    this.postDown.postDownload('evalute-server/evalute/evalute/studentExam/exportEvaluteExcel', obj);
  }

  // 新增编辑返回
  back(num) {
    this.mainStatus = num;
    this.mapOfCheckedId = {};

    if(num == 1) {
      delete this.pageInfoStu.filters['examCourseId'.toString()];
      delete this.pageInfoStu.filters['searchType'.toString()];
      this.evaluteList = [];
    } else if(num == 2) {
      this.pageStu(this.pageInfoStu)
    }
  }
}

class TopSearchObj {
  semesterId?: string;
  schoolYear?: string;
  number?: string;
  name?: string;
  teacherName?: string;
  classesName?:string;
}
class TopSearchStu {
  studentNumber?: string;
  studentName?: string;
}



